<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmitForm">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, inject } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { useMessage } from '@/hooks/web/useMessage';
  import { formSchema } from './data';

  import { getStorageSelectList, createStorage } from '@/api/app/setting';

  export default defineComponent({
    name: 'CloudSettingModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const tab_id: any = inject('tab_id');
      const { createMessage } = useMessage();

      // 配置表单
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 120,
        baseColProps: { span: 24 },
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      // 配置弹窗
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ minHeight: 1, canFullscreen: false, confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }

        const treeData = await getStorageSelectList(tab_id.value);
        updateSchema([
          {
            field: 'region',
            componentProps: { treeData },
          },
          {
            field: 'appid',
            ifShow: () => tab_id.value == 4,
          },
          {
            field: 'accessKey',
            ifShow: () => tab_id.value >= 5,
          },
          {
            field: 'secretKey',
            ifShow: () => tab_id.value >= 5,
          },
        ]);
      });

      const getTitle = computed(() => '添加云空间');

      // 提交表单
      async function handleSubmitForm() {
        try {
          const values = await validate();
          setModalProps({ canFullscreen: false, confirmLoading: true });

          await createStorage(tab_id.value, values)
            .then(() => {
              createMessage.success('添加成功');
            })
            .catch(() => {});

          closeModal();
          emit('success');
        } finally {
          setModalProps({ canFullscreen: false, confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmitForm };
    },
  });
</script>
